package com.ronri.ams.sample;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cz.nongyetongv5.R;
import com.cz.nongyetongv5.application.InitApplication;
import com.ronri.CustomDialog;
import com.ronri.ams.SystemEnvironmental;
import com.ronri.ams.bean.SampleBean;
import com.ronri.common.StringManager;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import static com.cz.nongyetongv5.application.InitApplication.gSampleInfo;


/**
 * 文件：ams.java
 * 包名：com.ronri.ams.sample;
 * 说明：
 * 作者：MS During
 * 日期：2017/5/27
 * 历史：
 */
public class activity_mutil_select_humen extends abstract_activity {

    // 用户
    private List<Humens> mHumens = new ArrayList<>();

    // Context
    private Context mContext = null;

    // 列表
    private ListView mlistView = null;

    // 删除按钮
    private Button mbtDelete = null;

    // 选择的内容
    private List<Integer> mSelectItem = new ArrayList<>();

    private List<Map<String, Object>> mItems = new ArrayList<>();

    private SelectAdapter mAdapter = null;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_mutil_select_with_delete);
        Log.i("aaa", "activity_mutil_select_humen");
        mContext = this;

        // 获取列表控件
        mlistView = (ListView) findViewById(R.id.list_data);
        mbtDelete = (Button) findViewById(R.id.btnDelete);

        Bundle bundle = getIntent().getExtras();

        String szTitle = bundle.getString("title");
        String szvTitle = bundle.getString("vtitle");

        String szSamples = bundle.getString("data");

        // 生成结果
        List<SampleBean> lObject = JSONArray.parseArray(szSamples, SampleBean.class);

        if (!StringManager.isEmpty(gSampleInfo.getUser_name()) &&
                !StringManager.isEmpty(gSampleInfo.getUser_name())) {
            String[] id = gSampleInfo.getSample_user().split(",");
            String[] name = gSampleInfo.getUser_name().split(",");

            int i = 0;
            for (String iTem : id) {
                // mSelectItem.add(i);

                Map<String, Object> ii = new HashMap<String, Object>();
                ii.put("listTitle", name[i++]);
                ii.put("listData", iTem);
                mItems.add(ii);
            }
        }

        // 设置标题
        setTitle(szTitle, szvTitle);

        // 初始化
        init();

        mAdapter = new SelectAdapter();
        mlistView.setAdapter(mAdapter);
        mlistView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                //获取条目
                CheckableFrameLayout linearLayout = (CheckableFrameLayout) view.findViewById(R.id.ll_contain);
                if (linearLayout.isChecked()) {
                    if (!mSelectItem.contains(i)) {
                        mSelectItem.add(i);
                    }
                } else {
                    if (mSelectItem.contains(i)) {
                        for (int pos = 0; pos < mSelectItem.size(); pos++) {
                            if (mSelectItem.get(pos) == i) {
                                mSelectItem.remove(pos);
                            }
                        }
                    }
                }
            }
        });

        /***
         * 删除按钮
         */
        mbtDelete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                // 选择大于0，则开始提示删除
                if (mSelectItem.size() > 0) {
                    CustomDialog.Builder builder = new CustomDialog.Builder(mContext);
                    builder.setMessage("是否确定删除？");
                    builder.setTitle("信息提示");
                    builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            try {
                                List<String> removeValue = new ArrayList<String>();

                                for (int i = 0; i < mSelectItem.size(); i++) {
                                    int nIndex = mSelectItem.get(i);
                                    String aa = mItems.get(nIndex).get("listTitle").toString();
                                    removeValue.add(aa.toLowerCase().trim());
                                }

                                for (Iterator<Map<String, Object>> it = mItems.iterator(); it.hasNext(); ) {
                                    Map<String, Object> obj = (Map<String, Object>) it.next();

                                    String szKey = obj.get("listTitle").toString();

                                    if (removeValue.contains(szKey.toLowerCase().trim())) {
                                        it.remove();
                                    }
                                }

                                mSelectItem.clear();
                                mAdapter.notifyDataSetChanged();
                                SaveData();
                            } catch (Exception ex) {
                                ex.printStackTrace();
                            }

                            dialog.dismiss();
                        }
                    });
                    builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    });

                    builder.create().show();
                }
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case SystemEnvironmental.Sample_INPUT_HUMEN_ADD: {
                    Bundle bundle = data.getExtras();
                    String szResult = bundle.getString("returnValue");
                    if (szResult != null) {
                        JSONArray jsonArray = JSON.parseArray(szResult);
                        if (jsonArray != null) {
                            int i = 0;
                            while (i < jsonArray.size()) {
                                JSONObject obj = (JSONObject) jsonArray.get(i);

                                String ss = obj.getString("name");
                                String id = obj.getInteger("id").toString();
                                boolean bFind = false;
                                if (obj.containsKey("name")) {
                                    for (Map<String, Object> ii : mItems) {
                                        Object iii = ii.get("listData");
                                        if (iii.toString().equals(id)) {
                                            bFind = true;
                                            break;
                                        }
                                    }

                                    if (!bFind) {
                                        Map<String, Object> ii = new HashMap<String, Object>();
                                        ii.put("listTitle", ss);
                                        ii.put("listData", id);
                                        mItems.add(ii);
                                    }
                                }
                                i++;
                            }

                            mAdapter.notifyDataSetChanged();
                            SaveData();
                        }
                    }
                }
                break;
            }
        }
    }

    /***
     * 保存到数据里
     */
    public void SaveData() {
        String szIds = "";
        String szNames = "";
        String szSplit = "";
        for (Map<String, Object> item : mItems) {
            szIds += szSplit + item.get("listData").toString();
            szNames += szSplit + item.get("listTitle").toString();
            szSplit = ",";
        }

        gSampleInfo.setUser_name(szNames);
        gSampleInfo.setSample_user(szIds);
    }

    @Override
    public boolean SureReturn() {
        Intent intent = new Intent(getApplicationContext(), activity_select_humen.class);
        Bundle bundle = new Bundle();
        String szRemoteAddress = InitApplication.SystemConfig.getBase().RemoteAddress(
                InitApplication.SystemConfig.getModule().getHumen().getAddress());
        /*** 设置远程地址 ***/
        bundle.putString("remoteAddress", szRemoteAddress);
        bundle.putString("filterKeyName", "name");
        bundle.putString("viewTitleName", "name");
        bundle.putInt("selectMode", ListView.CHOICE_MODE_MULTIPLE);
        bundle.putString("title", "抽样人员");
        bundle.putString("vtitle", "确定");
        bundle.putString("vid", gSampleInfo.getSample_user());
        bundle.putString("value", gSampleInfo.getUser_name());

        intent.putExtras(bundle);

        startActivityForResult(intent, SystemEnvironmental.Sample_INPUT_HUMEN_ADD);
        return false;
    }

    @Override
    public boolean CancelReturn() {
        if(mItems.size()<1){
            Toast.makeText(this,"请至少选择一名抽样人员", Toast.LENGTH_SHORT).show();
            return false;
        }else{
            setResult(RESULT_OK);
            return super.CancelReturn();
        }
    }

    /****
     * 用户
     */
    class Humens {
        public int id = 0;
        public String name = "";
    }

    public class SelectAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            return mItems.size();
        }

        @Override
        public String getItem(int position) {
            for (Map.Entry<String, Object> entry : mItems.get(position).entrySet()) {
                if (entry.getKey().equals("listTitle")) {
                    return entry.getValue().toString();
                }
            }
            return "";
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder = null;
            int iSelect = -1;

            if (convertView == null) {
                holder = new ViewHolder();
                convertView = LayoutInflater.from(mContext).inflate(R.layout.v_default_single_select, null);

                holder.iv_select = (CheckableImageView) convertView.findViewById(R.id.imageSimple);
                holder.listTitle = (TextView) convertView.findViewById(R.id.listTitle);

                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }

            holder.listTitle.setText(getItem(position));

            for (Map.Entry<String, Object> entry : mItems.get(position).entrySet()) {
                if (entry.getKey().equals("selected")) {
                    if (((boolean) entry.getValue())) {
                        iSelect = 1;
                    }else {
                        iSelect = -1;
                    }
                }else {
                    iSelect = -1;
                }
            }
            if (iSelect == 1) {
                holder.iv_select.setChecked(true);
            } else {
                holder.iv_select.setChecked(false);
            }
            return convertView;
        }
    }

    private class ViewHolder {
        CheckableImageView iv_select;
        TextView listTitle;
    }

}
